<template>
  <div class="jenkins-audit-container">
    <!-- 星空背景 -->
    <div class="stars"></div>
    <div class="stars2"></div>
    <div class="stars3"></div>

    <!-- 透明玻璃容器 -->
    <div class="glass-container">
      <div class="page-header">
        <h2 class="page-title">
          <i class="fa fa-jenkins"></i>
          Jenkins集成历史
        </h2>
      </div>

      <!-- 工具栏：操作按钮 -->
      <div class="toolbar-section glass-effect">
        <div class="toolbar-buttons">
          <button class="glass-button" @click="refreshAudit">
            <i class="fa fa-refresh"></i>
            刷新
          </button>
          <button class="glass-button" @click="exportAudit">
            <i class="fa fa-download"></i>
            导出
          </button>
        </div>
      </div>

      <!-- 过滤器 -->
      <div class="filters-section glass-effect">
        <div class="filters-row">
          <div class="filter-item">
            <label>项目</label>
            <select v-model="selectedProject" class="glass-input" @change="onProjectChange">
              <option value="">全部项目</option>
              <option v-for="project in projects" :key="project.id" :value="project.id">
                {{ project.name }}
              </option>
            </select>
          </div>

          <div class="filter-item">
            <label>环境</label>
            <select v-model="selectedEnvironment" class="glass-input" @change="onEnvironmentChange">
              <option value="">全部环境</option>
              <option v-for="env in environments" :key="env.id" :value="env.id">
                {{ env.name }}
              </option>
            </select>
          </div>

          <div class="filter-item">
            <label>操作类型</label>
            <select v-model="selectedOperation" class="glass-input">
              <option value="">全部操作</option>
              <option value="jenkins_server_create">服务器创建</option>
              <option value="jenkins_server_update">服务器更新</option>
              <option value="jenkins_server_delete">服务器删除</option>
              <option value="jenkins_server_test">连接测试</option>
              <option value="jenkins_job_create">任务创建</option>
              <option value="jenkins_job_update">任务更新</option>
              <option value="jenkins_job_delete">任务删除</option>
              <option value="jenkins_job_sync">任务同步</option>
              <option value="jenkins_build_trigger">构建触发</option>
              <option value="jenkins_build_abort">构建中止</option>
            </select>
          </div>

          <div class="filter-item">
            <label>操作结果</label>
            <select v-model="selectedResult" class="glass-input">
              <option value="">全部结果</option>
              <option value="success">成功</option>
              <option value="failed">失败</option>
            </select>
          </div>

          <div class="filter-item">
            <label>时间范围</label>
            <input
              type="date"
              v-model="dateRange.start"
              class="glass-input"
              placeholder="开始日期"
            />
          </div>

          <div class="filter-item">
            <label>&nbsp;</label>
            <input
              type="date"
              v-model="dateRange.end"
              class="glass-input"
              placeholder="结束日期"
            />
          </div>

          <div class="filter-item">
            <label>搜索</label>
            <input
              type="text"
              v-model="searchText"
              class="glass-input"
              placeholder="搜索用户、操作等..."
            />
          </div>
        </div>
      </div>

      <!-- 审计记录表格 -->
      <div class="audit-table-container glass-effect">
        <div class="table-header">
          <div class="header-cell">时间</div>
          <div class="header-cell">操作类型</div>
          <div class="header-cell">操作用户</div>
          <div class="header-cell">项目/环境</div>
          <div class="header-cell">Jenkins服务器</div>
          <div class="header-cell">结果</div>
          <div class="header-cell">操作</div>
        </div>

        <div class="table-body">
          <div
            v-for="audit in filteredAudits"
            :key="audit.id"
            class="table-row"
            :class="{
              'row-success': audit.result === 'success',
              'row-failed': audit.result === 'failed'
            }"
          >
            <div class="table-cell">
              {{ formatDate(audit.created_at) }}
            </div>

            <div class="table-cell">
              <span class="operation-badge" :class="getOperationClass(audit.operation_type)">
                {{ audit.operation_type_display }}
              </span>
            </div>

            <div class="table-cell">
              {{ audit.user_username || 'System' }}
            </div>

            <div class="table-cell">
              <div v-if="audit.project_name || audit.environment_name">
                <div v-if="audit.project_name">{{ audit.project_name }}</div>
                <div v-if="audit.environment_name" class="env-tag">{{ audit.environment_name }}</div>
              </div>
              <span v-else>-</span>
            </div>

            <div class="table-cell">
              {{ audit.jenkins_server_name || '-' }}
            </div>

            <div class="table-cell">
              <span
                class="result-badge"
                :class="{ 'result-success': audit.result === 'success', 'result-failed': audit.result === 'failed' }"
              >
                {{ audit.result === 'success' ? '成功' : '失败' }}
              </span>
            </div>

            <div class="table-cell">
              <div class="action-buttons">
                <button class="glass-button small" @click="viewDetails(audit)">
                  <i class="fa fa-eye"></i>
                  详情
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredAudits.length === 0" class="empty-state">
          <i class="fa fa-file-text empty-icon"></i>
          <h3>暂无审计记录</h3>
          <p>在选定的条件下没有找到相关的Jenkins操作记录</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>
        <div class="pagination-buttons">
          <button
            class="glass-button"
            :disabled="pagination.current <= 1"
            @click="changePage(pagination.current - 1)"
          >
            上一页
          </button>
          <button
            class="glass-button"
            :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)"
            @click="changePage(pagination.current + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <div v-if="detailModalVisible" class="modal-overlay" @click="closeDetailModal">
      <div class="modal-content glass-effect" @click.stop>
        <div class="modal-header">
          <h3>操作详情</h3>
          <button class="close-button" @click="closeDetailModal">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="modal-body" v-if="selectedAudit">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label>操作时间：</label>
                <span>{{ formatDate(selectedAudit.created_at) }}</span>
              </div>
              <div class="detail-item">
                <label>操作类型：</label>
                <span>{{ selectedAudit.operation_type_display }}</span>
              </div>
              <div class="detail-item">
                <label>操作用户：</label>
                <span>{{ selectedAudit.user_username || 'System' }}</span>
              </div>
              <div class="detail-item">
                <label>操作结果：</label>
                <span
                  class="result-badge"
                  :class="{ 'result-success': selectedAudit.result === 'success', 'result-failed': selectedAudit.result === 'failed' }"
                >
                  {{ selectedAudit.result === 'success' ? '成功' : '失败' }}
                </span>
              </div>
            </div>
          </div>

          <div class="detail-section" v-if="selectedAudit.project_name || selectedAudit.environment_name">
            <h4>关联信息</h4>
            <div class="detail-grid">
              <div class="detail-item" v-if="selectedAudit.project_name">
                <label>项目：</label>
                <span>{{ selectedAudit.project_name }}</span>
              </div>
              <div class="detail-item" v-if="selectedAudit.environment_name">
                <label>环境：</label>
                <span>{{ selectedAudit.environment_name }}</span>
              </div>
              <div class="detail-item" v-if="selectedAudit.jenkins_server_name">
                <label>Jenkins服务器：</label>
                <span>{{ selectedAudit.jenkins_server_name }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section" v-if="selectedAudit.details && Object.keys(selectedAudit.details).length > 0">
            <h4>详细信息</h4>
            <pre class="detail-json">{{ JSON.stringify(selectedAudit.details, null, 2) }}</pre>
          </div>

          <div class="detail-section" v-if="selectedAudit.error_message">
            <h4>错误信息</h4>
            <div class="error-message">{{ selectedAudit.error_message }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, onMounted, ref, watch } from 'vue'

// 响应式数据
const audits = ref([])
const projects = ref([])
const environments = ref([])
const selectedProject = ref('')
const selectedEnvironment = ref('')
const selectedOperation = ref('')
const selectedResult = ref('')
const searchText = ref('')
const dateRange = ref({
  start: '',
  end: ''
})

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0
})

const detailModalVisible = ref(false)
const selectedAudit = ref(null)

// 计算属性
const filteredAudits = computed(() => {
  return audits.value
})

// 方法
const refreshAudit = async () => {
  await loadAudits()
  ElMessage.success('审计记录已刷新')
}

const exportAudit = () => {
  ElMessage.info('导出功能开发中...')
}

const onProjectChange = () => {
  pagination.value.current = 1
  loadAudits()
}

const onEnvironmentChange = () => {
  pagination.value.current = 1
  loadAudits()
}

const viewDetails = (audit: any) => {
  selectedAudit.value = audit
  detailModalVisible.value = true
}

const closeDetailModal = () => {
  detailModalVisible.value = false
  selectedAudit.value = null
}

const changePage = (page: number) => {
  pagination.value.current = page
  loadAudits()
}

const getOperationClass = (operationType: string) => {
  const operationClasses = {
    'jenkins_server_create': 'op-create',
    'jenkins_server_update': 'op-update',
    'jenkins_server_delete': 'op-delete',
    'jenkins_server_test': 'op-test',
    'jenkins_job_create': 'op-create',
    'jenkins_job_update': 'op-update',
    'jenkins_job_delete': 'op-delete',
    'jenkins_job_sync': 'op-sync',
    'jenkins_build_trigger': 'op-build',
    'jenkins_build_abort': 'op-abort'
  }
  return operationClasses[operationType] || 'op-default'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// API调用
const loadAudits = async () => {
  try {
    const token = localStorage.getItem('token')

    // 构建查询参数
    const params = new URLSearchParams()
    if (selectedProject.value) params.append('project_id', selectedProject.value)
    if (selectedEnvironment.value) params.append('environment_id', selectedEnvironment.value)
    if (selectedOperation.value) params.append('operation_type', selectedOperation.value)
    if (selectedResult.value) params.append('result', selectedResult.value)
    if (dateRange.value.start) params.append('start_date', dateRange.value.start)
    if (dateRange.value.end) params.append('end_date', dateRange.value.end)
    if (searchText.value) params.append('search', searchText.value)
    params.append('page', pagination.value.current.toString())
    params.append('page_size', pagination.value.pageSize.toString())

    const url = `/api/jenkins/jenkins-audit/${params.toString() ? '?' + params.toString() : ''}`

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Token ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取审计记录失败')
    }

    const data = await response.json()
    audits.value = data.results || []
    pagination.value.total = data.count || 0
  } catch (error) {
    console.error('加载审计记录失败:', error)
    ElMessage.error(`加载审计记录失败: ${error.message}`)
  }
}

const loadProjects = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('/api/jenkins/projects/', {
      method: 'GET',
      headers: {
        'Authorization': `Token ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const data = await response.json()
      projects.value = data.results || data
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
  }
}

const loadEnvironments = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('/api/jenkins/environments/', {
      method: 'GET',
      headers: {
        'Authorization': `Token ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const data = await response.json()
      environments.value = data.results || data
    }
  } catch (error) {
    console.error('加载环境列表失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadAudits()
  loadProjects()
  loadEnvironments()

  // 监听过滤条件变化，自动重新加载数据
  watch([selectedOperation, selectedResult, dateRange], () => {
    pagination.value.current = 1
    loadAudits()
  }, { deep: true })

  // 搜索防抖
  let searchTimeout: any = null
  watch(searchText, () => {
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }
    searchTimeout = setTimeout(() => {
      pagination.value.current = 1
      loadAudits()
    }, 500)
  })
})
</script>

<style scoped>
/* 使用与GitLab审计页面完全相同的样式 */
.jenkins-audit-container {
  min-height: 100vh;
  padding: 24px 24px 100px 24px;
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
}

/* 星空背景动画 */
.stars, .stars2, .stars3 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.stars {
  background: transparent url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="0.5" fill="white" opacity="0.8"/><circle cx="80" cy="40" r="0.3" fill="white" opacity="0.6"/><circle cx="40" cy="60" r="0.4" fill="white" opacity="0.7"/><circle cx="90" cy="80" r="0.2" fill="white" opacity="0.5"/><circle cx="10" cy="90" r="0.6" fill="white" opacity="0.9"/></svg>') repeat;
  animation: move-stars 50s linear infinite;
}

.stars2 {
  background: transparent url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="30" cy="10" r="0.3" fill="white" opacity="0.4"/><circle cx="70" cy="70" r="0.5" fill="white" opacity="0.8"/><circle cx="15" cy="50" r="0.2" fill="white" opacity="0.6"/></svg>') repeat;
  animation: move-stars 100s linear infinite;
}

.stars3 {
  background: transparent url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="60" cy="30" r="0.4" fill="white" opacity="0.7"/><circle cx="25" cy="75" r="0.3" fill="white" opacity="0.5"/></svg>') repeat;
  animation: move-stars 150s linear infinite;
}

@keyframes move-stars {
  from { transform: translateY(0px); }
  to { transform: translateY(-2000px); }
}

.glass-container {
  background: rgba(164, 244, 186, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.08);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(164, 244, 186, 0.15);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(164, 244, 186, 0.1);
}

/* 按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.15);
  border: 1px solid rgba(164, 244, 186, 0.4);
  border-radius: 8px;
  color: #a4f4ba;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(5px);
  box-shadow: 0 4px 15px rgba(164, 244, 186, 0.1);
}

.glass-button:hover {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.6);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(164, 244, 186, 0.2);
}

.glass-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.glass-button.small {
  padding: 6px 12px;
  font-size: 12px;
}

/* 输入框样式 */
.glass-input {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  padding: 8px 12px;
  color: #fff;
  font-size: 14px;
  width: 100%;
  transition: all 0.3s ease;
}

.glass-input:focus {
  outline: none;
  border-color: rgba(164, 244, 186, 0.6);
  background: rgba(164, 244, 186, 0.15);
  box-shadow: 0 0 0 2px rgba(164, 244, 186, 0.1);
}

.glass-input option {
  background: #1a1a2e;
  color: #fff;
}

/* 页面标题 */
.page-title {
  color: #fff;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title i {
  color: #a4f4ba;
}

/* 工具栏样式 */
.toolbar-section {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 12px;
}

.toolbar-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 过滤器样式 */
.filters-section {
  margin-bottom: 30px;
  padding: 20px;
  border-radius: 12px;
}

.filters-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  align-items: end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-item label {
  color: #a4f4ba;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

/* 表格样式 */
.audit-table-container {
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  background: rgba(164, 244, 186, 0.1);
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.header-cell {
  padding: 12px 8px;
  color: #fff;
  font-weight: 600;
  font-size: 14px;
}

.table-body {
  /* 移除固定高度和滚动条，让表格自然展示 */
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1);
  transition: all 0.3s ease;
}

.table-row:hover {
  background: rgba(164, 244, 186, 0.05);
}

.table-row.row-success {
  border-left: 3px solid #51cf66;
}

.table-row.row-failed {
  border-left: 3px solid #ff6b6b;
}

.table-cell {
  padding: 8px;
  display: flex;
  align-items: center;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}

/* 操作类型标签 */
.operation-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.op-create { background: rgba(76, 175, 80, 0.2); color: #4caf50; }
.op-update { background: rgba(33, 150, 243, 0.2); color: #2196f3; }
.op-delete { background: rgba(244, 67, 54, 0.2); color: #f44336; }
.op-test { background: rgba(255, 193, 7, 0.2); color: #ffc107; }
.op-sync { background: rgba(156, 39, 176, 0.2); color: #9c27b0; }
.op-build { background: rgba(0, 188, 212, 0.2); color: #00bcd4; }
.op-abort { background: rgba(255, 87, 34, 0.2); color: #ff5722; }
.op-default { background: rgba(158, 158, 158, 0.2); color: #9e9e9e; }

/* 结果标签 */
.result-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.result-success {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.result-failed {
  background: rgba(244, 67, 54, 0.2);
  color: #f44336;
}

/* 环境标签 */
.env-tag {
  font-size: 12px;
  color: rgba(164, 244, 186, 0.8);
  background: rgba(164, 244, 186, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
  margin-top: 2px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-icon {
  font-size: 48px;
  color: rgba(164, 244, 186, 0.3);
  margin-bottom: 16px;
}

.empty-state h3 {
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 8px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(164, 244, 186, 0.05);
  border-radius: 12px;
  margin-top: 20px;
}

.pagination-info {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 12px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: rgba(26, 26, 46, 0.95);
  border-radius: 16px;
  padding: 24px;
  max-width: 800px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.modal-header h3 {
  color: #fff;
  margin: 0;
  font-size: 20px;
}

.close-button {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-button:hover {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  color: #a4f4ba;
  margin-bottom: 12px;
  font-size: 16px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-item label {
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
  min-width: 80px;
}

.detail-item span {
  color: rgba(255, 255, 255, 0.9);
}

.detail-json {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 8px;
  padding: 16px;
  color: rgba(255, 255, 255, 0.9);
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  overflow-x: auto;
}

.error-message {
  background: rgba(244, 67, 54, 0.1);
  border: 1px solid rgba(244, 67, 54, 0.3);
  border-radius: 8px;
  padding: 12px;
  color: #f44336;
  font-size: 14px;
  line-height: 1.4;
}
</style>
